<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import { onMounted } from 'vue'
import { io, Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted } from 'vue'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { ref } from 'vue'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { nextTick } from 'vue'
import { showToast } from 'vant'
import { provide } from 'vue'

defineOptions({
  name: 'RoomPage'
})

// updateMsgStatus 消息已读

// getChatMsgList 获取聊天记录

/**
 * 发http请求获取订单详情 渲染状态栏对应的一些数据
 * 1. 页面挂载时候 - 订单详情
 * 2. 订单状态发生变化的时候 - 重新获取订单详情
 */

const userStore = useUserStore()
const initMsg = ref(true)
const route = useRoute()
const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()
const lastTime = ref('')
const loadConsultOrderDetail = async () => {
  const { data } = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = data
}
const changeEva = (score: number) => {
  // 找到未评价的卡片
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    // 消息类型改成已评价
    item.msgType = MsgType.CardEva
    // 提供evaluateDoc 提供分数字段
    item.msg.evaluateDoc = {
      score
    }
  }
}
provide('consult', consult)
provide('changeEva', changeEva)
// vue3多个生命周期函数，比如onMounted都会执行
onMounted(() => {
  loadConsultOrderDetail()
})
let socket: Socket
// 此处的onMounted都处理socket相关逻辑 包括监听事件
onMounted(() => {
  // 建立连接
  // 地址传的基地址
  socket = io(baseURL, {
    auth: {
      // 注意这里的token 要写成Bearer ${token}
      token: `Bearer ${userStore.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('connect', () => {
    console.log('connect')
    list.value = []
  })
  socket.on('disconnect', () => {
    console.log('disconnect')
  })
  socket.on('connect_error', () => {
    console.log('connect_error')
  })
  // chatMsgList 接收聊天记录
  socket.on('chatMsgList', async ({ data }: { data: TimeMessages[] }) => {
    // console.log('ws 后端主动给我们的发的消息', data)
    // 数据结构长这样： [{createTime: '9:00', items: 对象（Message）数组}, {createTime: '10:00', items: 对象（Message）数组}]
    const result: Message[] = []
    data.forEach((item, idx) => {
      if (idx === 0) {
        lastTime.value = item.createTime
      }
      result.push(
        {
          createTime: item.createTime,
          id: item.createTime,
          msg: {
            content: item.createTime
          },
          msgType: MsgType.Notify
        },
        ...item.items
      )
    })
    list.value.unshift(...result)
    loading.value = false
    // 没有历史数据，给用户提示，没有数据
    if (data.length === 0) {
      return showToast('没有数据了')
    }
    if (initMsg.value) {
      initMsg.value = false
      await nextTick()
      window.scrollTo(0, document.body.scrollHeight)
    }
  })
  // statusChange 接收订单状态改变
  socket.on('statusChange', () => {
    // console.log('状态变化了')
    loadConsultOrderDetail()
  })
  // receiveChatMsg 接收消息
  socket.on('receiveChatMsg', async (res) => {
    // console.log('receiveChatMsg', res)
    // list列表增加消息数据
    list.value.push(res)
    // dom的更新是异步的 vue2 this.$nextTick
    /**
     * vue3 nextTick两种语法
     * 方案一 参数传回调函数，在回调函数里写逻辑
     * 方案二 await nextTick() 因为nextTick返回值是Promise
     */
    // nextTick(() => {
    //   window.scrollTo(0, document.body.scrollHeight)
    // })

    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
  })
})
onUnmounted(() => {
  socket.close()
})
const onSendText = (val: string) => {
  // console.log('儿子通知我的', val)
  // sendChatMsg 发送消息
  socket.emit('sendChatMsg', {
    from: userStore.user?.id,
    to: consult.value?.docInfo?.id, //医生id
    msgType: MsgType.MsgText,
    msg: {
      content: val
    }
  })
}
const onSendImg = (val: Image) => {
  // console.log('儿子传给我的图片', val)
  socket.emit('sendChatMsg', {
    from: userStore.user?.id,
    to: consult.value?.docInfo?.id, //医生id
    msgType: MsgType.MsgImage,
    msg: {
      picture: val
    }
  })
}
const loading = ref(false)
const onRefresh = () => {
  // setTimeout(() => {
  //   showToast('刷新成功')
  //   loading.value = false
  // }, 1000)
  socket.emit('getChatMsgList', 20, lastTime.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <room-action
      @send-text="onSendText"
      @send-img="onSendImg"
      :disabled="consult?.status !== OrderType.ConsultChat"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
